<template>
  <div class="volunteer-review-page">
    <el-card class="review-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><UserFilled /></el-icon>
            <span>待审核志愿者申请</span>
            <el-tag v-if="applications.length > 0" type="warning" effect="plain" class="header-badge">
              {{ applications.length }} 条待审核
            </el-tag>
          </div>
          <div class="header-right">
            <el-button :icon="Refresh" @click="loadPendingApplications" :loading="loading">
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <div class="review-content">
        <!-- 搜索和筛选 -->
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索姓名、电话、地址"
            clearable
            :prefix-icon="Search"
            @input="handleSearch"
            style="width: 300px"
          />
        </div>

        <!-- 申请列表 -->
        <el-table
          :data="filteredApplications"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          :empty-text="loading ? '加载中...' : '暂无待审核的申请'"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          
          <el-table-column prop="name" label="姓名" width="100" align="center" />
          
          <el-table-column prop="phone" label="电话" width="120" align="center" />
          
          <el-table-column prop="address" label="地址" min-width="150">
            <template #default="{ row }">
              <span 
                v-if="row.address" 
                class="clickable-text"
                @click="showFieldDetail('地址', row.address)"
                :title="row.address.length > 30 ? '点击查看完整地址' : ''"
              >
                {{ row.address.length > 30 ? row.address.substring(0, 30) + '...' : row.address }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="experience" label="经验" min-width="120">
            <template #default="{ row }">
              <span 
                v-if="row.experience" 
                class="clickable-text"
                @click="showFieldDetail('志愿者经验', row.experience)"
                :title="row.experience.length > 20 ? '点击查看完整内容' : ''"
              >
                {{ row.experience.length > 20 ? row.experience.substring(0, 20) + '...' : row.experience }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="skills" label="技能特长" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.skills">{{ row.skills }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="availability" label="可用时间" width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.availability">{{ row.availability }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="whyVolunteer" label="申请动机" min-width="150">
            <template #default="{ row }">
              <span 
                v-if="row.whyVolunteer" 
                class="clickable-text"
                @click="showFieldDetail('申请动机', row.whyVolunteer)"
                :title="row.whyVolunteer.length > 30 ? '点击查看完整内容' : ''"
              >
                {{ row.whyVolunteer.length > 30 ? row.whyVolunteer.substring(0, 30) + '...' : row.whyVolunteer }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="preferredTasks" label="倾向任务" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <div v-if="row.preferredTasks" class="tasks-tags">
                <el-tag
                  v-for="(task, index) in getTaskList(row.preferredTasks)"
                  :key="index"
                  size="small"
                  type="primary"
                  effect="plain"
                  style="margin-right: 4px; margin-bottom: 4px"
                >
                  {{ task }}
                </el-tag>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="220" align="center" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                :icon="View"
                @click="showDetail(row)"
              >
                详情
              </el-button>
              <el-button
                type="success"
                size="small"
                :icon="Check"
                @click="handleReview(row.id, 1)"
                :loading="reviewingId === row.id"
              >
                通过
              </el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Close"
                @click="handleReview(row.id, 2)"
                :loading="reviewingId === row.id"
              >
                驳回
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 字段详情对话框 -->
        <el-dialog
          v-model="fieldDetailDialogVisible"
          :title="fieldDetailTitle"
          width="600px"
          :close-on-click-modal="true"
        >
          <div class="field-detail-content">
            <div class="detail-text">{{ fieldDetailContent }}</div>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="fieldDetailDialogVisible = false">关闭</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 完整详情对话框 -->
        <el-dialog
          v-model="detailDialogVisible"
          title="申请详情"
          width="800px"
          :close-on-click-modal="false"
        >
          <div v-if="currentApplication" class="detail-content">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="姓名">
                {{ currentApplication.name }}
              </el-descriptions-item>
              <el-descriptions-item label="电话">
                {{ currentApplication.phone }}
              </el-descriptions-item>
              <el-descriptions-item label="地址" :span="2">
                {{ currentApplication.address }}
              </el-descriptions-item>
              <el-descriptions-item label="志愿者经验" :span="2">
                {{ currentApplication.experience || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="技能特长" :span="2">
                {{ currentApplication.skills || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="可用时间" :span="2">
                {{ currentApplication.availability || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="申请动机" :span="2">
                {{ currentApplication.whyVolunteer || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="倾向任务" :span="2">
                <div v-if="currentApplication.preferredTasks" class="tasks-tags">
                  <el-tag
                    v-for="(task, index) in getTaskList(currentApplication.preferredTasks)"
                    :key="index"
                    size="small"
                    type="primary"
                    effect="plain"
                    style="margin-right: 8px; margin-bottom: 8px"
                  >
                    {{ task }}
                  </el-tag>
                </div>
                <span v-else>-</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="detailDialogVisible = false">关闭</el-button>
              <el-button
                type="success"
                :icon="Check"
                @click="handleReview(currentApplication?.id, 1)"
                :loading="reviewingId === currentApplication?.id"
              >
                通过
              </el-button>
              <el-button
                type="danger"
                :icon="Close"
                @click="handleReview(currentApplication?.id, 2)"
                :loading="reviewingId === currentApplication?.id"
              >
                驳回
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  UserFilled,
  Refresh,
  Search,
  Check,
  Close,
  View
} from '@element-plus/icons-vue';

export default {
  name: 'VolunteerReview',
  components: {
    UserFilled,
    Refresh,
    Search,
    Check,
    Close,
    View
  },
  data() {
    return {
      loading: false,
      applications: [],
      searchKeyword: '',
      reviewingId: null,
      detailDialogVisible: false,
      currentApplication: null,
      fieldDetailDialogVisible: false,
      fieldDetailTitle: '',
      fieldDetailContent: ''
    };
  },
  computed: {
    filteredApplications() {
      if (!this.searchKeyword) {
        return this.applications;
      }
      const keyword = this.searchKeyword.toLowerCase();
      return this.applications.filter(app => {
        return (
          (app.name && app.name.toLowerCase().includes(keyword)) ||
          (app.phone && app.phone.includes(keyword)) ||
          (app.address && app.address.toLowerCase().includes(keyword))
        );
      });
    }
  },
  mounted() {
    this.loadPendingApplications();
  },
  methods: {
    async loadPendingApplications() {
      this.loading = true;
      try {
        const res = await axios.get('http://localhost:8080/api/admin/volunteer/pending');
        if (res.data.code === 200) {
          this.applications = res.data.data || [];
        } else {
          ElMessage.error(res.data.msg || '加载申请列表失败');
        }
      } catch (error) {
        console.error('加载申请列表失败:', error);
        if (error.response && error.response.data && error.response.data.msg) {
          ElMessage.error(error.response.data.msg);
        } else {
          ElMessage.error('加载申请列表失败，请检查网络连接');
        }
      } finally {
        this.loading = false;
      }
    },

    async handleReview(id, status) {
      const statusText = status === 1 ? '通过' : '驳回';
      
      ElMessageBox.confirm(
        `确认${statusText}该志愿者申请吗？`,
        '提示',
        {
          type: 'warning',
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        }
      )
        .then(async () => {
          this.reviewingId = id;
          
          // 尝试多种参数格式
          const attempts = [
            // 尝试1: 使用请求体，id 和 status（数字）
            { method: 'body', params: { id: id, status: status } },
            // 尝试2: 使用 URL 参数，id 和 status
            { method: 'params', params: { id: id, status: status } },
            // 尝试3: 使用请求体，applicationId
            { method: 'body', params: { applicationId: id, status: status } },
            // 尝试4: 使用 URL 参数，applicationId
            { method: 'params', params: { applicationId: id, status: status } },
            // 尝试5: 使用请求体，字符串类型
            { method: 'body', params: { id: String(id), status: String(status) } },
            // 尝试6: 使用 URL 参数，字符串类型
            { method: 'params', params: { id: String(id), status: String(status) } },
            // 尝试7: 使用请求体，volunteerApplicationId
            { method: 'body', params: { volunteerApplicationId: id, status: status } },
            // 尝试8: 使用 URL 参数，volunteerApplicationId
            { method: 'params', params: { volunteerApplicationId: id, status: status } }
          ];
          
          let lastError = null;
          
          for (let i = 0; i < attempts.length; i++) {
            try {
              const attempt = attempts[i];
              console.log(`尝试 ${i + 1} (${attempt.method}):`, attempt.params);
              
              let res;
              if (attempt.method === 'params') {
                // 使用 URL 参数
                res = await axios.post(
                  'http://localhost:8080/api/admin/volunteer/review',
                  null,
                  {
                    params: attempt.params,
                    headers: {
                      'Content-Type': 'application/json'
                    }
                  }
                );
              } else {
                // 使用请求体
                res = await axios.post(
                  'http://localhost:8080/api/admin/volunteer/review',
                  attempt.params,
                  {
                    headers: {
                      'Content-Type': 'application/json'
                    }
                  }
                );
              }

              if (res.data.code === 200) {
                ElMessage.success(res.data.msg || `申请已${statusText}`);
                await this.loadPendingApplications();
                this.reviewingId = null;
                return; // 成功，退出
              } else {
                console.warn(`尝试 ${i + 1} 返回非200状态:`, res.data);
                lastError = new Error(res.data.msg || `${statusText}失败`);
              }
            } catch (error) {
              console.error(`尝试 ${i + 1} 失败:`, {
                status: error.response?.status,
                data: error.response?.data,
                message: error.message
              });
              lastError = error;
              
              // 如果不是 400 错误，说明可能是其他问题，不再尝试其他格式
              if (error.response?.status && error.response.status !== 400) {
                break;
              }
            }
          }
          
          // 所有尝试都失败，显示错误信息
          if (lastError?.response?.data) {
            const errorData = lastError.response.data;
            const errorMsg = errorData.msg || errorData.message || errorData.error || '参数格式错误';
            ElMessage.error(`审核失败：${errorMsg}`);
            console.error('最终错误详情:', {
              status: lastError.response.status,
              data: errorData,
              path: errorData.path,
              timestamp: errorData.timestamp
            });
          } else {
            ElMessage.error(`${statusText}失败，请检查网络连接或联系管理员`);
            console.error('所有尝试都失败，最后错误:', lastError);
          }
          
          this.reviewingId = null;
        })
        .catch(() => {
          // 用户取消
        });
    },

    handleSearch() {
      // 搜索功能由 computed 属性 filteredApplications 处理
    },

    getTaskList(tasks) {
      if (!tasks) return [];
      if (typeof tasks === 'string') {
        return tasks.split(',').filter(t => t.trim());
      }
      if (Array.isArray(tasks)) {
        return tasks;
      }
      return [];
    },

    showDetail(application) {
      this.currentApplication = application;
      this.detailDialogVisible = true;
    },

    showFieldDetail(title, content) {
      this.fieldDetailTitle = title;
      this.fieldDetailContent = content || '-';
      this.fieldDetailDialogVisible = true;
    }
  }
};
</script>

<style scoped>
.volunteer-review-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 88px);
}

.review-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.review-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 30px;
  border-radius: 12px 12px 0 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 20px;
  font-weight: 600;
}

.header-icon {
  font-size: 24px;
}

.header-badge {
  margin-left: 8px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.review-content {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tasks-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.detail-content {
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f5f7fa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #fafafa;
}

:deep(.el-table .el-table__row:hover) {
  background: #f0f9ff;
}

/* 可点击文本样式 */
.clickable-text {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
  text-decoration-style: dotted;
  transition: all 0.3s ease;
}

.clickable-text:hover {
  color: #66b1ff;
  text-decoration-style: solid;
}

/* 字段详情对话框 */
.field-detail-content {
  padding: 20px 0;
  max-height: 500px;
  overflow-y: auto;
}

.detail-text {
  font-size: 14px;
  line-height: 1.8;
  color: #303133;
  white-space: pre-wrap;
  word-wrap: break-word;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

/* 响应式 */
@media (max-width: 1200px) {
  .review-content {
    padding: 15px;
  }

  :deep(.el-table) {
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .volunteer-review-page {
    padding: 15px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-right {
    width: 100%;
    justify-content: flex-end;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-section .el-input {
    width: 100% !important;
  }
}
</style>
